import dayjs from 'dayjs'

// 格式化时间
export const formatTime = (time) => {
    let year = dayjs(time).year();
    let month = dayjs(time).month() + 1;
    let date = dayjs(time).date();
    let hour = dayjs(time).hour();
    let minute = dayjs(time).minute();

    if (month < 10) {
        month = '0' + month;
    }
    if (date < 10) {
        date = '0' + date;
    }
    if (hour < 10) {
        hour = '0' + hour;
    }
    if (minute < 10) {
        minute = '0' + minute;
    }
    return year + '-' + month + '-' + date + ' ' + hour + ':' + minute;
}

// 获取当前日期和一周前日期 格式为YYYY-MM-DD
export const formatDate = (date) => {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}  

// 计算一个日期n小时后的日期
export const addHours = (date, hours) => {
    var d = new Date(date);
    d.setHours(d.getHours() + hours);
    return d;
}

// 格式化时间 2024080710=》2024-08-07 10:00
export const formatTimeStr = (time) => {
    let year = time.slice(0, 4);
    let month = time.slice(4, 6);
    let date = time.slice(6, 8);
    let hour = time.slice(8, 10);

    return year + '-' + month + '-' + date + ' ' + hour + ':00';
}

// 判断两个日期相差几个小时
export const diffHours = (date1, date2) => {
    // 传入的时间格式为YYYY-MM-DD HH:mm
    let d1 = new Date(date1);
    let d2 = new Date(date2);
    let diff = d2 - d1;
    return diff / 1000 / 60 / 60;
}